package com.etymgiko.lyricscollectionseam.session;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.framework.EntityHome;

import com.etymgiko.lyricscollectionseam.entity.Song;

/**
 * @author Ivan Holub
 */
@Name("songHome")
@Scope(ScopeType.EVENT)
public class SongHome extends EntityHome<Song> {

	@In(create = true)
	private SongManager songManager;

	@In(create = true)
	private ArtistHome artistHome;

	private String songTitleParam;

	private String songLyricsParam;

	public String getSongTitle() {
		if (songTitleParam != null) {
			return songTitleParam;
		}
		return getInstance() == null ? null : getInstance().getTitle();
	}

	public void setSongTitle(String songTitle) {
		this.songTitleParam = songTitle;
	}

	public String getSongLyrics() {
		if (songLyricsParam != null) {
			return songLyricsParam;
		}
		return getInstance() == null ? null : getInstance().getLyrics();
	}

	public void setSongLyrics(String songLyrics) {
		this.songLyricsParam = songLyrics;
	}

	public void setSongId(Long id) {
		setId(id);
	}

	public void setArtistId(Long id) {
		artistHome.setArtistId(id);
	}

	public Long getArtistId() {
		return artistHome.getArtistId();
	}

	public Long getSongId() {
		return (Long) getId();
	}

	@Override
	protected Song createInstance() {
		Song song = new Song();
		song.setArtist(artistHome.getInstance());
		return song;
	}

	public String save() {
		boolean isSuccess = false;

		if (isManaged()) {
			if (getInstance().getTitle().equals(songTitleParam)) {
				isSuccess = true;
			}
		}
		if (!isSuccess) {
			if (songManager.findSong(getInstance().getArtist().getId(),
					songTitleParam) != null) {
				//error, song with such title already exist
				FacesMessage message = new FacesMessage(
						"Song with such title already exists");
				FacesContext.getCurrentInstance().addMessage(
						"songForm:songTitle", message);
            } else {
                //ok, song with such title doesn't exist
                isSuccess = true;
            }
		}
		
		if (isSuccess) {
			getInstance().setTitle(songTitleParam);
			getInstance().setLyrics(songLyricsParam);

			if (isManaged()) {
				update();
			} else {
				persist();
			}

			return "success";
		}
		
		return null;
	}

}
